package com.magiccompass.alipay.barcode.util;

import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.magiccompass.alipay.barcode.constants.BusinessLogicConstants;

@Component
public class EmailUtil {
	private JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
	
	public void sendSimpleEmail(String receiverEmailAddress,String title,String body){
		setMailSenderEnvParameter();
		try{
			SimpleMailMessage message = new SimpleMailMessage();
	        message.setTo(receiverEmailAddress);
	        message.setSubject(title);
	        message.setText(body);
	        mailSender.send(message);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendEmailWithAttachment(String receiverEmailAddress,String title,String body,String attachmentPath){
		setMailSenderEnvParameter();
		MimeMessage message = mailSender.createMimeMessage();		
		try{
			MimeMessageHelper helper = new MimeMessageHelper(message, true);		
			helper.setFrom(BusinessLogicConstants.SYSTEM_NOREPLY_EMAIL_ADDRESS);
			helper.setTo(receiverEmailAddress);
			helper.setSubject(title);
			helper.setText(body);
		
			FileSystemResource file = new FileSystemResource(attachmentPath);
			helper.addAttachment(file.getFilename(), file);
			mailSender.send(message);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendEmailWithAttachment(String receiverEmailAddress,String title,String body,String attachmentPath, String[] ccArray){
		setMailSenderEnvParameter();
		MimeMessage message = mailSender.createMimeMessage();		
		try{
			MimeMessageHelper helper = new MimeMessageHelper(message, true);		
			helper.setFrom(BusinessLogicConstants.SYSTEM_NOREPLY_EMAIL_ADDRESS);
			helper.setTo(receiverEmailAddress);
			helper.setSubject(title);
			helper.setText(body);
			
			helper.setCc(ccArray);
		
			FileSystemResource file = new FileSystemResource(attachmentPath);
			helper.addAttachment(file.getFilename(), file);
			mailSender.send(message);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setMailSenderEnvParameter(){
		mailSender.setDefaultEncoding("UTF-8");
		mailSender.setHost("imap.gmail.com");
		java.util.Properties prop = new java.util.Properties();
		prop.setProperty("mail.smtp.auth", "true");
		prop.setProperty("mail.smtp.starttls.enable", "true");		
		mailSender.setJavaMailProperties(prop);
		mailSender.setPassword(BusinessLogicConstants.SYSTEM_EMAIL_SENDER_PASSWORD);
		mailSender.setPort(587);
		//mailSender.setProtocol("smtp");
		mailSender.setUsername(BusinessLogicConstants.SYSTEM_EMAIL_SENDER_ADDRESS);		
	}
	
	public static void main(String[] args){		
	}
}